#include"string.h"

namespace sty
{
	const size_t string::npos = -1; 
	void string:: push_back(char c)
	{
		if (_size == _capacity)
		{
			reserve(_capacity == 0 ? 4 : 2 * _capacity);
		}
		_str[_size] = c;
		++_size;
		_str[_size] = '\0';
	}
	void string::reserve(size_t n)
	{
		if (n > _capacity)
		{
			char* tmp = new char[n + 1];
			strcpy(tmp, _str);
			delete[] _str;
			_str = tmp;
			_capacity = n;
		}
	}
	string& string::operator+=(char c)
	{
		push_back(c);
		return *this;
	}
	void string::append(const char* str)
	{
		size_t len = strlen(str);
		if (_size + len > _capacity)
		{
			reserve(_size + len > _capacity * 2 ? _size + len : _capacity * 2);
		}
		strcpy(_str + _size, str);
		_size += len;
	}
	string& string::operator+=(const char* str)
	{
		append(str);
		return *this;
	}
	string& string::insert(size_t pos, char c)
	{
		assert(pos <= _size);
		if (_size == _capacity)
		{
			reserve(_capacity == 0 ? 4 : 2 * _capacity);
		}
		size_t end = _size+1;
		while (end > pos)
		{
			_str[end] = _str[end-1];
			--end;
		}
		_str[pos] = c;
		++_size;
		return *this; 
	}

	string& string::insert(size_t pos, const char* str)
	{
		assert(pos <= _size);
		size_t len = strlen(str);
		if (_size + len > _capacity)
		{
			reserve(_size + len > _capacity * 2 ? _size + len : _capacity * 2);
		}
		size_t end = _size + len;
		while (pos+len-1 < end)
		{
			_str[end] = _str[end - len];
			--end;
		}
		for (size_t i = 0; i < len; i++)
		{
			_str[pos + i] = str[i];
		}
		_size += len;
		return *this;
	}

	string& string::erase(size_t pos, size_t len)
	{
		assert(pos < _size);
		if (len > _size - pos)
		{
			_str[pos] = '\0';
			_size = pos;
		}
		else
		{
			for (size_t i = pos+len; i <= _size; i++)
			{
				_str[i - len] = _str[i];
			}
			_size -= len;
		}
		return *this;
	}

	size_t string::find(char c, size_t pos)const
	{
		assert(pos < _size);
		for (size_t i = 0; i < _size; i++)
		{
			if (_str[i] == c)
			{
				return i;
			}
		}
		return npos;
	}
	size_t string::find(const char* s, size_t pos)const
	{
		assert(pos < _size);
		const char* ptr = strstr(_str+pos, s);
		if (ptr == nullptr)
		{
			return npos;
		}
		else
		{
			return ptr-_str;
		}
	}

	        //relational operators

	bool string::operator<(const string& s)
	{
		return strcmp(_str, s.c_str())<0;
	}

	bool string::operator<=(const string& s)
	{
		return *this < s || *this == s; 
	}

	bool string::operator>(const string& s)
	{
		return !(*this <= s);
	}

	bool string::operator>=(const string& s)
	{
		return !(*this > s);
	}

	bool string::operator==(const string& s)
	{
		return strcmp(_str, s.c_str()) == 0;
	}

	bool string::operator!=(const string& s)
	{
		return !(*this == s);
	}

	//ostream& operator<<(ostream& _cout, const sty::string& s)
	//{

	//}

	//istream& operator>>(istream& _cin, sty::string& s)
	//{

	//}
}